import os
from datetime import datetime, timedelta

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger

from .config import config
from .databus import capture_datetimes, device
from .db import db
from .entity import Log
from .model.program import Program, ProgramType
from .util import capture_to_datetime, generate_hex_str
from .window_api import window_api


class Status:
    def __init__(self) -> None:
        self.last_capture_datetime = datetime(2000, 1, 1)

status = Status()

def timelog_task()  -> None:
    log: Log = device.time_logger.get_log()
    # 精确到秒即可
    log.time = datetime.fromtimestamp(int(log.time.timestamp()))
    print(log)
    window_api.log(f'{log}')
    now = log.time

    # last_program = program_service.get_last()
    last_program :Program = db.session.query(Program).order_by(Program.id.desc()).first()
    if last_program is not None and log.program == last_program.name and log.title == last_program.title \
        and (now - last_program.end_time <= timedelta(seconds=30)):
        # program_service.update_end_time(last_program.id, now)
        last_program.end_time = now
        db.session.commit()

        # 距离上次截图的时间过了60s就截图
        if now - status.last_capture_datetime >= timedelta(seconds=config.capture_interval):
            capture = device.time_logger.save_current_capture()
            capture_datetimes.append(capture_to_datetime(capture))
            status.last_capture_datetime = now
    else:
        # program_type_service.save_if_absent(log.program)
        program_type = db.session.query(ProgramType).filter_by(name=log.program).first()

        if not program_type:
            ProgramType(name=log.program, color=generate_hex_str(6)).save()

        if last_program is not None and now - last_program.end_time <= timedelta(seconds=10):
            begin_time = last_program.end_time
        else:
            begin_time = now
        Program(log.program, log.title, begin_time, now).save()
        # 直接截图
        capture = device.time_logger.save_current_capture()
        capture_datetimes.append(capture_to_datetime(capture))
        status.last_capture_datetime = now


def notify():
    # print('notify')
    device.notifier.notify_by_toast('到点了！！', 'TimeLog', 5)


scheduler = BackgroundScheduler()
scheduler.add_job(timelog_task, IntervalTrigger(seconds=config.timelog_interval))
jobs = []
